<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备指纹识别 - 调试页面</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        .button:hover {
            background: #0056b3;
        }
        .button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .info-item {
            margin: 8px 0;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 4px;
            word-break: break-all;
        }
        .label {
            font-weight: bold;
            color: #495057;
        }
        .value {
            color: #333;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
        .log {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            height: 200px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
        .error { color: #dc3545; }
        .success { color: #28a745; }
        .warning { color: #ffc107; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 设备指纹识别调试工具</h1>
        <p>用来测试设备指纹识别功能，无需依赖后端服务器。</p>
        
        <div>
            <button class="button" onclick="testCryptoSupport()">测试 Crypto API</button>
            <button class="button" onclick="collectBasicInfo()">收集基础信息</button>
            <button class="button" onclick="generateFingerprint()">生成设备指纹</button>
            <button class="button" onclick="testHashFunction()">测试哈希函数</button>
            <button class="button" onclick="clearLogs()">清除日志</button>
        </div>
    </div>

    <div class="container">
        <h2>🖥️ 设备信息</h2>
        <div id="deviceInfo">
            <p>点击"收集基础信息"按钮开始...</p>
        </div>
    </div>

    <div class="container">
        <h2>🔐 设备指纹</h2>
        <div id="fingerprint">
            <p>点击"生成设备指纹"按钮开始...</p>
        </div>
    </div>

    <div class="container">
        <h2>📋 操作日志</h2>
        <div class="log" id="logs"></div>
    </div>

    <script>
        // 日志记录函数
        function log(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const logElement = document.getElementById('logs');
            const logClass = type === 'error' ? 'error' : type === 'success' ? 'success' : type === 'warning' ? 'warning' : '';
            logElement.innerHTML += `<div class="${logClass}">[${timestamp}] ${message}</div>`;
            logElement.scrollTop = logElement.scrollHeight;
            console.log(`[${type.toUpperCase()}] ${message}`);
        }

        // 清除日志
        function clearLogs() {
            document.getElementById('logs').innerHTML = '';
        }

        // 测试 Crypto API 支持
        function testCryptoSupport() {
            log('🔍 测试 Crypto API 支持...');
            
            if (typeof crypto === 'undefined') {
                log('❌ crypto 对象不存在', 'error');
                return false;
            }
            
            log('✅ crypto 对象存在', 'success');
            
            if (!crypto.subtle) {
                log('❌ crypto.subtle 不支持', 'error');
                return false;
            }
            
            log('✅ crypto.subtle 支持', 'success');
            
            if (!crypto.subtle.digest) {
                log('❌ crypto.subtle.digest 不支持', 'error');
                return false;
            }
            
            log('✅ crypto.subtle.digest 支持', 'success');
            log('🎉 Crypto API 完全支持！', 'success');
            return true;
        }

        // 收集基础设备信息
        function collectBasicInfo() {
            log('📱 开始收集基础设备信息...');
            
            const info = {
                screenResolution: `${screen.width}x${screen.height}`,
                timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
                language: navigator.language || navigator.userLanguage,
                platform: navigator.platform,
                userAgent: navigator.userAgent,
                colorDepth: screen.colorDepth,
                pixelDepth: screen.pixelDepth,
                cookieEnabled: navigator.cookieEnabled,
                doNotTrack: navigator.doNotTrack,
                hardwareConcurrency: navigator.hardwareConcurrency || 'unknown',
                timestamp: new Date().toISOString()
            };

            // 显示设备信息
            const deviceInfoElement = document.getElementById('deviceInfo');
            deviceInfoElement.innerHTML = '';
            
            Object.keys(info).forEach(key => {
                const div = document.createElement('div');
                div.className = 'info-item';
                div.innerHTML = `<span class="label">${formatLabel(key)}:</span> <span class="value">${info[key]}</span>`;
                deviceInfoElement.appendChild(div);
            });

            window.deviceInfo = info;
            log('✅ 基础设备信息收集完成', 'success');
            return info;
        }

        // 格式化标签
        function formatLabel(key) {
            const labelMap = {
                screenResolution: '屏幕分辨率',
                timezone: '时区',
                language: '语言',
                platform: '平台',
                userAgent: '用户代理',
                colorDepth: '颜色深度',
                pixelDepth: '像素深度',
                cookieEnabled: 'Cookie支持',
                doNotTrack: '请勿跟踪',
                hardwareConcurrency: '硬件并发',
                timestamp: '时间戳'
            };
            return labelMap[key] || key;
        }

        // 备选哈希函数
        function fallbackHash(text) {
            log('🔧 使用备选哈希算法...');
            
            let hash1 = 0;
            let hash2 = 0;
            let hash3 = 0;
            
            for (let i = 0; i < text.length; i++) {
                const char = text.charCodeAt(i);
                
                // 第一种哈希
                hash1 = ((hash1 << 5) - hash1) + char;
                hash1 = hash1 & hash1; // 转换为32位整数
                
                // 第二种哈希
                hash2 = ((hash2 << 3) + hash2) + char;
                hash2 = hash2 & hash2;
                
                // 第三种哈希
                hash3 = ((hash3 * 31) + char) % 982451653;
            }
            
            // 组合三个哈希值
            const combined = Math.abs(hash1).toString(16) + 
                            Math.abs(hash2).toString(16) + 
                            Math.abs(hash3).toString(16);
            
            // 截取固定长度并补充时间戳确保唯一性
            const timestamp = Date.now().toString(16);
            const result = (combined + timestamp).substring(0, 32);
            
            log(`✅ 备选哈希生成成功: ${result}`, 'success');
            return result;
        }

        // 测试哈希函数
        async function testHashFunction() {
            log('🔐 测试哈希函数...');
            const testData = 'test-data-' + Date.now();
            
            // 测试 Web Crypto API
            if (testCryptoSupport()) {
                try {
                    const encoder = new TextEncoder();
                    const data = encoder.encode(testData);
                    const hashBuffer = await crypto.subtle.digest('SHA-256', data);
                    const hashArray = Array.from(new Uint8Array(hashBuffer));
                    const cryptoHash = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
                    log(`✅ Web Crypto API 哈希: ${cryptoHash}`, 'success');
                } catch (error) {
                    log(`❌ Web Crypto API 失败: ${error.message}`, 'error');
                }
            }
            
            // 测试备选哈希
            const fallbackResult = fallbackHash(testData);
            log(`✅ 备选哈希结果: ${fallbackResult}`, 'success');
        }

        // 生成设备指纹
        async function generateFingerprint() {
            log('🔍 开始生成设备指纹...');
            
            // 先收集设备信息
            if (!window.deviceInfo) {
                collectBasicInfo();
            }

            // 生成额外信息
            const additionalInfo = {
                canvasFingerprint: getCanvasFingerprint(),
                webglFingerprint: getWebGLFingerprint(),
                fonts: 'simplified-font-check' // 简化版本
            };

            const combinedInfo = { ...window.deviceInfo, ...additionalInfo };
            const dataString = JSON.stringify(combinedInfo);
            
            log('📊 设备信息组合完成，正在生成指纹...');
            
            // 生成指纹
            let fingerprint = '';
            if (testCryptoSupport()) {
                try {
                    const encoder = new TextEncoder();
                    const data = encoder.encode(dataString);
                    const hashBuffer = await crypto.subtle.digest('SHA-256', data);
                    const hashArray = Array.from(new Uint8Array(hashBuffer));
                    fingerprint = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
                    log('✅ 使用 Web Crypto API 生成指纹', 'success');
                } catch (error) {
                    log(`❌ Web Crypto API 失败，使用备选方案: ${error.message}`, 'warning');
                    fingerprint = fallbackHash(dataString);
                }
            } else {
                log('⚠️ Web Crypto API 不支持，使用备选哈希', 'warning');
                fingerprint = fallbackHash(dataString);
            }

            // 显示指纹
            document.getElementById('fingerprint').innerHTML = `
                <div class="info-item">
                    <span class="label">设备指纹:</span> 
                    <span class="value">${fingerprint}</span>
                </div>
                <div class="info-item">
                    <span class="label">指纹长度:</span> 
                    <span class="value">${fingerprint.length} 字符</span>
                </div>
                <div class="info-item">
                    <span class="label">生成时间:</span> 
                    <span class="value">${new Date().toLocaleString()}</span>
                </div>
            `;

            log(`🎉 设备指纹生成完成: ${fingerprint.substring(0, 8)}...`, 'success');
            return fingerprint;
        }

        // 获取 Canvas 指纹
        function getCanvasFingerprint() {
            try {
                const canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                
                ctx.textBaseline = 'top';
                ctx.font = '14px Arial';
                ctx.fillStyle = '#f60';
                ctx.fillRect(125, 1, 62, 20);
                ctx.fillStyle = '#069';
                ctx.fillText('华南师范大学VR展馆 🏛️', 2, 15);
                ctx.fillStyle = 'rgba(102, 204, 0, 0.7)';
                ctx.fillText('设备指纹识别', 4, 45);

                return canvas.toDataURL();
            } catch (error) {
                log(`Canvas 指纹获取失败: ${error.message}`, 'warning');
                return 'canvas_not_supported';
            }
        }

        // 获取 WebGL 指纹
        function getWebGLFingerprint() {
            try {
                const canvas = document.createElement('canvas');
                const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
                
                if (!gl) {
                    return 'webgl_not_supported';
                }

                const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
                const vendor = gl.getParameter(debugInfo?.UNMASKED_VENDOR_WEBGL || gl.VENDOR);
                const renderer = gl.getParameter(debugInfo?.UNMASKED_RENDERER_WEBGL || gl.RENDERER);
                
                return `${vendor}~${renderer}`;
            } catch (error) {
                log(`WebGL 指纹获取失败: ${error.message}`, 'warning');
                return 'webgl_error';
            }
        }

        // 页面加载时自动运行基础测试
        window.addEventListener('load', () => {
            log('🚀 设备指纹调试工具已加载');
            log('💡 提示：请先点击"测试 Crypto API"检查浏览器支持情况');
        });
    </script>
</body>
</html>
